package com.pb.filter;

import com.pb.utils.CurrentHolder;
import com.pb.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取请求路径
        String path = request.getRequestURI();///login
        //2、判断是否是登录请求，如果是登录请求，放行
        if(path.contains("/login")){
            log.info("登录请求，放行：{}",path);
            filterChain.doFilter(request,response);
            return;
        }
        //3、获取请求头中的token
        String token = request.getHeader("token");
        //4、判断token是否为空，如果为空，返回401
        if(token == null|| token.isEmpty()){
            log.info("请求头token为空，返回401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //5、如果token不为空，解析token，如果解析失败，返回401
        try {
            Claims claims = JwtUtils.parseJWT(token);
            CurrentHolder.setCurrentId(Integer.valueOf(claims.get("id").toString()));
            log.info("解析令牌成功，当前用户id为：{}",claims.get("id"));
        } catch (Exception e) {
            log.info("解析令牌失败，返回401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //6、校验通过，放行
        log.info("令牌校验通过，放行");
        filterChain.doFilter(request,response);

        //7、在当前线程中移除当前用户id
        CurrentHolder.remove();
    }
}
